package com.singleton.hungry;


import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 饿汉式单例  静态常量
 * 1 构造方法私有
 * 2 创建常量对象
 * 3 构造 public static getInstance方法，返回常量对象
 */
public class Singleton_01 {
    public static void main(String[] args) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        //测试
        Singleton1 instance1 = Singleton1.getInstance();
        Singleton1 instance2 = Singleton1.getInstance();
        //引用类型的 == 比较的是地址值
        System.out.println(instance1 == instance2);
        System.out.println("instance1 hashcode : "+instance1);
        System.out.println("instance2 hashcode : "+instance2);

        //通过反射打破单例模式
        //breakSingleton();
    }

    private static void breakSingleton() throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //尝试通过反射打破单例模式
        Class<Singleton1> singleton1Class = Singleton1.class;
        //得到public的构造方法
        Constructor<?>[] constructors = singleton1Class.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor.getName());
        }
        //得到私有的构造方法
        Constructor<Singleton1> declaredConstructor = singleton1Class.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        Singleton1 singleton1 = declaredConstructor.newInstance();
        Singleton1 singleton2 = declaredConstructor.newInstance();
        System.out.println(singleton1 == singleton2);
        System.out.println("singleton1 hashcode : " + singleton1);
        System.out.println("singleton2 hashcode : " + singleton2);
    }
}


/***
 * 饿汉式 静态常量
 */
class Singleton1 {

    //1 构造器私有 不让别人创建
    private Singleton1() {

    }

    //2 不然别人创建，我直接自己创建一个
    private static final Singleton1 instance = new Singleton1();

    //3 提供一个public 静态方法，返回实例对象
    public static Singleton1 getInstance() {
        return instance;
    }

}
